// pages/my-orders/my-orders.ts
import { getMyOrderList } from '../../../api/publish';
import { goToPage, PAGES } from '../../../config/pages';
import { getDemandCategoryNames } from '../../../config/product-categories';

Page({
  data: {
    orders: [] as any[],
    page: 1,
    limit: 10,
    total: 0,
    loading: false,
    hasMore: true,
    searchValue: '',
    // 筛选条件
    selectedCategory: '', // all, material, processing
  },

  onLoad() {
    this.loadOrders();
  },

  onShow() {
    // 刷新数据
    this.loadOrders(true);
  },

  // 页面滚动到底部时触发
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadOrders();
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadOrders(true).finally(() => {
      wx.stopPullDownRefresh();
    });
  },

  async loadOrders(refresh: boolean = false) {
    if (this.data.loading) return;
    
    if (refresh) {
      this.setData({
        page: 1,
        orders: [],
        hasMore: true
      });
    }

    this.setData({ loading: true });

    try {
      const params: any = {
        page: this.data.page,
        limit: this.data.limit,
      };

      // 添加筛选条件
      if (this.data.selectedCategory && this.data.selectedCategory !== 'all') {
        params.category = this.data.selectedCategory;
      }
      // 添加搜索关键词
      if (this.data.searchValue) {
        params.keyword = this.data.searchValue;
      }

      const res = await getMyOrderList(params);

      if (res.status === 200 && res.data) {
        const list = res.data.list || [];
        const formattedList = list.map((item: any) => {
          // item 是参与记录，包含 publish 对象（单据信息）
          const publish = item.publish || {};
          return {
            id: item.id,
            publish_id: item.publish_id,
            publish: publish,
            product_model: publish.product_model,
            product_category: publish.product_category,
            product_name: publish.product_name,
            province: publish.province,
            city: publish.city,
            remark: publish.remark,
            category: publish.category, // 添加category字段
            formatted_date: this.formatDate(publish.add_time),
            participated_at: this.formatDate(item.add_time),
          };
        });

        const newOrders = refresh ? formattedList : [...this.data.orders, ...formattedList];
        
        this.setData({
          orders: newOrders,
          total: res.data.count || 0,
          hasMore: newOrders.length < (res.data.count || 0),
          page: this.data.page + 1,
          loading: false
        });
      } else {
        wx.showToast({
          title: res.msg || '加载失败',
          icon: 'none',
        });
        this.setData({ loading: false });
      }
    } catch (error: any) {
      console.error('加载我的接单失败:', error);
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.message || '加载失败'),
        icon: 'none',
      });
      this.setData({ loading: false });
    }
  },

  formatDate(dateStr: string): string {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  goToDetail(e: any) {
    const { id } = e.currentTarget.dataset;
    if (id) {
      goToPage(PAGES.DEMAND_DETAIL, { id });
    }
  },

  onSearchInput(e: any) {
    this.setData({ searchValue: e.detail.value });
  },

  // 执行搜索
  performSearch(e: any) {
    // 如果是事件对象，获取输入值；如果是字符串，直接使用
    const keyword = typeof e === 'string' ? e : (e.detail?.value || '');
    this.setData({
      searchValue: keyword,
      page: 1,
      orders: [],
      hasMore: true
    });
    this.loadOrders(true);
  },

  // 清空搜索
  clearSearch() {
    this.setData({
      searchValue: '',
      page: 1,
      orders: [],
      hasMore: true
    });
    this.loadOrders(true);
  },

  // 显示分类筛选弹窗
  showCategoryModal() {
    const demandCategories = getDemandCategoryNames();
    const categories = ['全部分类', ...demandCategories];
    wx.showActionSheet({
      itemList: categories,
      success: (res) => {
        const categoryValues = ['all', ...demandCategories];
        this.setData({
          selectedCategory: categoryValues[res.tapIndex],
          page: 1,
          orders: [],
          hasMore: true
        });
        this.loadOrders(true);
      }
    });
  },
});

